package com.dlwx.firefighting.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dlwx.firefighting.R;
import com.dlwx.firefighting.adapter.CartAdapter;
import com.dlwx.firefighting.bean.CartBean;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.inter.CartInter;
import com.dlwx.firefighting.utils.DialogUtils;
import com.dlwx.firefighting.utils.LogUtils;
import com.dlwx.firefighting.utils.SPUtils;
import com.dlwx.firefighting.utils.ToastUtils;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.view.CommonHeader;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CartActivity extends AppCompatActivity implements CartInter {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.cart_recycler)
    LRecyclerView cartRecycler;
    @BindView(R.id.commit_ll)
    LinearLayout commitLl;
    @BindView(R.id.toshoping_tv)
    TextView toshopingTv;
    @BindView(R.id.money_tv)
    TextView moneyTv;
    @BindView(R.id.commit_tv)
    TextView commitTv;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private CartAdapter cartAdapter;
    private List<CartBean> datas = new ArrayList<>();
    private List<CartBean> choseDatas = new ArrayList<>();
    private boolean isChooseALL = false;
    private String userId;
    private int page = 1;
    private int requestNum = 10;
    private int count = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        ButterKnife.bind(this);
        userId = (String) SPUtils.get(this, Constant.USER_ID, "");
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!choseDatas.isEmpty()){
            choseDatas.clear();
        }
        selectAllImg.setImageResource(R.mipmap.select);
        isChooseALL = false;
        SpannableString str = new SpannableString("合计:" + getString(R.string.rmb) + 0);
        str.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.fuzhu_red)), 3, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        moneyTv.setText(str);
        refresh();


    }

    private void getDatas() {
        OkGo.<String>post(Constant.CARTLIST)
                .tag(this)
                .params("user", userId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        DealResult dealResult = new DealResult();
//                        List<CartBean> beans = dealResult.deal(CartActivity.this, response, new TypeToken<BaseBean<CartBean>>() {
//                        }.getType());
//                        if(beans.isEmpty()){
//                            toShoping();
////                            return;
//                        }
//                        cartAdapter.addAll(beans);
//                        cartRecycler.refreshComplete(requestNum);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(CartActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    private void toShoping(){
        commitLl.setVisibility(View.GONE);
        cartRecycler.setVisibility(View.GONE);
        toshopingTv.setVisibility(View.VISIBLE);
        toshopingTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }


    public void initView() {
        SpannableString str = new SpannableString("合计:" + getString(R.string.rmb) + "0");
        str.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.fuzhu_red)), 3, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        moneyTv.setText(str);
        tvMiddleTitle.setText("购物车");
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        cartAdapter = new CartAdapter(this, this);
        cartRecycler.setLayoutManager(new LinearLayoutManager(this));
        cartAdapter.setDataList(datas);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(cartAdapter);
        cartRecycler.setAdapter(lRecyclerViewAdapter);
        cartRecycler.setPullRefreshEnabled(true);
        DividerDecoration divider = new DividerDecoration.Builder(this)
                .setHeight(R.dimen.divider_height_6)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.app_bg_color)
                .build();
        cartRecycler.addItemDecoration(divider);
        initBanner();
        //设置下拉刷新
        cartRecycler.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
//        cartRecycler.refresh();
        //设置上拉加载更多
     /*   mainRecyclerview.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (page < totalPage) {
                    page++;

                } else {
                    mainRecyclerview.setNoMore(true);
                }
            }
        });
          */
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                startActivity(new Intent(this, VideoDetailActivity.class));
            }
        });

    }

    //创建header
     ImageView selectAllImg;
    private void initBanner() {
        CommonHeader header = new CommonHeader(this, R.layout.cart_header);
        TextView selectAllTv = (TextView) header.findViewById(R.id.select_all_tv);
        TextView deleteAllTv = (TextView) header.findViewById(R.id.delete_all_tv);
        LinearLayout allLl = (LinearLayout) header.findViewById(R.id.all_ll);
        selectAllImg = (ImageView) header.findViewById(R.id.select_all_img);
        allLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isChooseALL) {
                    selectAllImg.setImageResource(R.mipmap.select);
                    isChooseALL = false;
                } else {
                    selectAllImg.setImageResource(R.mipmap.select_true);
                    isChooseALL = true;
                }
                handleAllCart(isChooseALL);
            }
        });
        deleteAllTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dropCart("", 2);
            }
        });
        lRecyclerViewAdapter.addHeaderView(header);
    }

    private void handleAllCart(boolean isChoose) {
        for (CartBean bean : cartAdapter.getDataList()) {
            bean.setChoose(isChoose);
        }
        lRecyclerViewAdapter.notifyDataSetChanged();
        if(isChoose){
            choseDatas.clear();
           choseDatas.addAll( cartAdapter.getDataList());
        }else{
            choseDatas.clear();
        }
        countMoney();
    }

    @OnClick({R.id.title_left_one_btn, R.id.tv_middle_title, R.id.toshoping_tv, R.id.commit_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                CartActivity.this.finish();
                break;
            case R.id.tv_middle_title:
                break;
            case R.id.toshoping_tv:
                break;
            case R.id.commit_tv:
                if(choseDatas.isEmpty()){
                    ToastUtils.toastForShort(CartActivity.this,"请先选取要结算的商品");
                    return;
                }
                Intent i=new Intent(CartActivity.this, OrderConfirmActivity.class);
                i.putExtra("id",receIds);
                startActivity(i);
               /* PayNowDialog dialog = new PayNowDialog(CartActivity.this);
                dialog.show();*/
                break;
        }
    }

    @Override
    public void addCart(CartBean item, int position) {
        cartAdapter.getDataList().get(position).setChoose(true);
        lRecyclerViewAdapter.notifyDataSetChanged();
        if(!choseDatas.contains(item)){
            choseDatas.add(item);
        }
        countMoney();
        cartChoseAll();
    }

    @Override
    public void removeCart(CartBean item, int position) {
        cartAdapter.getDataList().get(position).setChoose(false);
        lRecyclerViewAdapter.notifyDataSetChanged();
        if(choseDatas.contains(item)){
            choseDatas.remove(item);
        }
        countMoney();
        cartChoseAll();
    }

    /**
     * 购物车是否被全选
     */
    private void cartChoseAll() {
        List<CartBean> lists = cartAdapter.getDataList();
        if(lists.isEmpty()){
            return;
        }
        for(CartBean bean:lists){
            if(!bean.isChoose()){
                selectAllImg.setImageResource(R.mipmap.select);
                return;
            }
        }
        selectAllImg.setImageResource(R.mipmap.select_true);
    }

    @Override
    public void deleteCart(CartBean item, int position) {
        dropCart(item.getRec_id(), 1);
    }

    public void dropCart(String id, int type) {
        //        1、删除购物车中某一个商品2、清空购物车
        DialogUtils.showProgressDlg(this,"");
        OkGo.<String>post(Constant.DROP_CART)
                .tag(this)
                .params("user", userId)
                .params("rec_id", id)
                .params("type", type)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
//                        DealResult dealResult = new DealResult();
//                        BaseBean bean=dealResult.dealBaseRes(CartActivity.this,response);
//                        if(bean==null){
//                         return;
//                        }
//                        if(bean.getStatus()==Constant.SUCESS){
//                            ToastUtils.toastForShort(CartActivity.this,"删除成功");
//                            cartAdapter.clear();
//                            lRecyclerViewAdapter.notifyDataSetChanged();
//                            getDatas();
//                        }else{
//                            ToastUtils.toastForShort(CartActivity.this,"删除失败");
//                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(CartActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }
    private String receIds;
    private void countMoney(){
        if(choseDatas.isEmpty()){
            SpannableString str = new SpannableString("合计:" + getString(R.string.rmb) + 0);
            str.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.fuzhu_red)), 3, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            moneyTv.setText(str);
            return;
        }
        float price=0;
        receIds="";
        for(CartBean bean:choseDatas){
            float f=Float.parseFloat(bean.getSubtotal());
            price=price+f;
            receIds=receIds+bean.getRec_id()+",";
        }
        if(receIds.endsWith(",")){
            receIds=receIds.substring(0,receIds.length()-1);
        }

        SpannableString str = new SpannableString("合计:" + getString(R.string.rmb) + price);
        str.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.fuzhu_red)), 3, str.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        moneyTv.setText(str);
    }

    /**
     * 刷新
     */
    public void refresh() {
        cartAdapter.clear();
        lRecyclerViewAdapter.notifyDataSetChanged();
        page=1;
        getDatas();
    }

//
    public void refresh1(int position, int number, String subtotal) {
        LogUtils.d("---"+position+number+subtotal);
       CartBean bean= cartAdapter.getDataList().get(position);
        bean.setGoods_number(number+"");
        bean.setSubtotal(subtotal);
        cartAdapter.getDataList().set(position,bean);
        lRecyclerViewAdapter.notifyItemChanged(lRecyclerViewAdapter.getAdapterPosition(false,position) , "jdsjlzx");
        lRecyclerViewAdapter.notifyDataSetChanged();

}

}
